<template>
	<view class="vercode-input__container">
		<input class="vercode-input__input" hold-keyboard :focus="_focus" :maxlength="length" @focus="onFocus($event)" type="number" @blur="onBlur($event)" v-model="_value"/>
		<view class="vercode-input__inner">
			<view v-for="(item, index) in length" class="vercode-input__item-box">
				<view :class="['vercode-input__item-wrapper', {'focus': _focus && cursor == index}]">
					<input  disabled class="vercode-input__item" :value="_value[index]" @click="onFocus($event)" />
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		name:"vercode-input",
		props: {
			length: {
				type: Number,
				default: 6
			},
			focus: {
				type: Boolean,
				default: false
			}
		},
		computed: {
			cursor() {
				return Math.min(this._value.length || 0, this.length)
			}
		},
		watch: {
			cursor: {
				handler: function(newVal, oldVal) {
					if(newVal >= this.length) {
						this._focus = false
						this.$emit("confirm", {detail: {value: this._value}})
					} 
				}
			},
			focus: {
				handler: function(newVal, oldVal) {
					this._focus = newVal
				}
			}
		},
		data() {
			return {
				_focus: false,
				_value: ""
			};
		},
		created() {
			this._focus = this.focus
		},
		methods: {
			reset: function() {
				this._value = ""
			},
			onFocus: function(event) {
				this._focus = true
				this.$emit("focus", event)
			},
			onBlur: function(event) {
				this._focus = false
				this.$emit("blur", event)
			},
		}
	}
</script>

<style>
	.vercode-input__container {
		position: relative;
	}
	
	.vercode-input__inner {
		width: 100%;
		display: flex;
		flex-direction: row;
		align-items: center;
		justify-content: center;
	}
	
	.vercode-input__input {
		position: absolute;
		left: 0;
		top: 0;
		width: 0;
		height: 0;
		color: black;
	}
	
	.vercode-input__item-box {
		position: relative;
		flex: 1;
		overflow: hidden;
		z-index: 999;
		margin: 0 6rpx;
	}
	
	.vercode-input__item-box:first-child {
		margin-left: 0rpx;
	}
	
	.vercode-input__item-box:last-child {
		margin-right: 0rpx;
	}
	
	.vercode-input__item-wrapper {
		position: relative;
		width: 100%;
		padding-top: 100%;
		background: red;
		border: thin solid #c7c7c7;
		border-radius: 10rpx;
		box-sizing: border-box;
		background: white;
		overflow: hidden;
	}
	
	.vercode-input__item-wrapper.focus {
		border-color: blue;
	}
	
	.vercode-input__item {
		position: absolute;
		left: 0;
		top: 0;
		width: 100%;
		height: 100%;
		text-align: center;
	}
</style>